//
//  HomeViewModel.m
//  mvvm
//
//  Created by zhtc-mac1 on 2017/11/29.
//  Copyright © 2017年 lixiaoyun. All rights reserved.
//

#import "HomeViewModel.h"
#import "homeModel.h"
@interface HomeViewModel ()

@property (strong, nonatomic) NSMutableArray *ViewModels; ///< 这个属性主要存储的是vm，上拉加载的时候追加，下拉刷新的时候清空。防止直接修改dataSource

@end

/// 弱引用，强引用
#define KLWeakSelf(weakSelf)  __weak typeof(&*self) weakSelf = self
#define KLStrongSelf(strongSelf)  __strong typeof(&*weakSelf) strongSelf = weakSelf

@implementation HomeViewModel


-(NSMutableArray *)ViewModels
{
    if (!_ViewModels) {
        _ViewModels = [NSMutableArray array];
    }
    return _ViewModels;
}

-(RACSignal *)requestSignal
{
    if (!_requestSignal) {
        KLWeakSelf(weakSelf);
        _requestSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            NSDictionary *parameters = @{@"page": @(1)};
            
            NSURLSessionTask *task =  [weakSelf httpRequestGetDataWithUrl:@"http://www.saitjr.com/api_for_test/static_article_list.php" params:parameters cacheBlock:nil successBlock:^(NSURLSessionDataTask *task, id resposeObject) {
                
                NSDictionary *articleArray = resposeObject[@"data"];
                for (NSString *key in articleArray) {
                    
                    homeModel *articleModel = [homeModel getHomeModelWithDict:articleArray[key]];
                    // 根据模型，初始化cell的vm
                   // HomePageCellViewModel *cellViewModel = [[HomePageCellViewModel alloc] initWithArticleModel:articleModel];
                    // 将cell的vm存入数组
                    [weakSelf.ViewModels addObject:articleModel];
                }
                // 完成数据处理后，赋值给dataSource
                weakSelf.dataSource = [weakSelf.ViewModels copy];
                [subscriber sendNext:weakSelf.dataSource];
                [subscriber sendCompleted];
               } failBlock:^(NSURLSessionDataTask *task, NSError *error) {
                
                   
               }];
            
            return [RACDisposable disposableWithBlock:^{
                
                [task cancel];
            }];;
        }];
    }
    
    return _requestSignal;
}

@end
